// utils/request.js
const { baseUrl, loginUrl, refreshTokenUrl} = require("../api/base")
const { cheakTokenExpired } = require('./funs')

const login = async () => {
	try {
		// 获取微信登录 code
		const code = await new Promise((resolve, reject) => {
			wx.login({
				success: (res) => {
					if (res.code) resolve(res.code)
					else reject(new Error('获取 code 失败'))
				},
				fail: (err) => reject(err) // 处理微信登录失败
			})
		})
		// 请求服务器获取 tokens
		const { token, refreshToken } = await new Promise((resolve, reject) => {
			wx.request({
				url: baseUrl + loginUrl,
				method: 'POST',
				data: { code },
				success: (res) => {
					if (res.statusCode >= 200 && res.statusCode < 300) {
						// 根据实际返回数据结构调整（示例：res.data.token）
						resolve(res.data)
					} else {
						reject(new Error(`请求失败，状态码：${res.statusCode}`))
					}
				},
				fail: (err) => reject(err) // 处理网络请求失败
			})
		})

		// 存储 token 到本地
		await Promise.all([
			new Promise((resolve, reject) => {
				wx.setStorage({
					key: 'token',
					data: token,
					success: resolve,
					fail: (err) => reject(new Error('存储 token 失败'))
				})
			}),
			new Promise((resolve, reject) => {
				wx.setStorage({
					key: 'refreshToken',
					data: refreshToken,
					success: resolve,
					fail: (err) => reject(new Error('存储 refreshToken 失败'))
				})
			})
		])

		console.log('登录成功')
	} catch (error) {
		console.error('登录失败:', error)
		throw error // 抛出错误供调用者处理
	}
}

const refreshToken = async (refreshToken) => {
	try {
		const res = await new Promise((resolve, reject) => {
			wx.request({
				url: baseUrl + refreshTokenUrl,
				method: 'POST',
				data: { refreshToken },
				success: (res) => {
					if (res.statusCode >= 200 && res.statusCode < 300) {
						resolve(res.data)
					} else {
						debugger
						reject(new Error(`请求失败，状态码：${res.statusCode}`))
					}
				},
				fail: (err) => {
					debugger

					reject(err)
				} // 处理网络请求失败
			})
		})
		// 假设响应格式为 { code: 200, data: { token, refreshToken } }
		if (res.code === 200) {
			wx.setStorageSync('token', res.data.token);
			wx.setStorageSync('refreshToken', res.data.refreshToken);
			return res.data.token; // 返回新 token
		} else {
			throw new Error(res.message || '刷新 Token 失败');
		}
	} catch (error) {
		// 刷新失败清除存储并重新登录
		wx.removeStorageSync('token');
		wx.removeStorageSync('refreshToken');
		throw error;
	}
}
class Request {
	constructor() {
		this.config = {
			baseUrl: baseUrl,
			timeout: 60000,
			header: {
				'Content-Type': 'application/json'
			},
			dataType: 'json',
			responseType: 'json'
		};

		// 拦截器
		this.requestInterceptors = [];
		this.responseInterceptors = [];

		// 绑定方法
		this.get = this._request('GET');
		this.post = this._request('POST');
		this.put = this._request('PUT');
		this.delete = this._request('DELETE');
	}

	// 创建请求方法
	_request(method) {
		return async (url, data = {}, config = {}) => {
			const mergedConfig = this._mergeConfig(config);
			return this._coreRequest({
				method,
				url,
				data,
				...mergedConfig
			});
		};
	}

	// 核心请求方法
	async _coreRequest(options) {
		try {
			// 合并配置
			const mergedOptions = {
				...this.config,
				...options,
				header: { ...this.config.header, ...options.header },
				url: this.config.baseUrl + options.url
			};

			// 请求拦截
			for (const interceptor of this.requestInterceptors) {
				await interceptor(mergedOptions);
			}
			// 发起请求
			const response = await new Promise((resolve, reject) => {
				wx.request({
					...mergedOptions,
					success: res => resolve(res),
					fail: err => reject(err),
					complete: () => mergedOptions.hideLoading || wx.hideLoading()
				});
			});

			// 响应拦截
			for (const interceptor of this.responseInterceptors) {
				await interceptor(response);
			}

			// 处理响应状态
			if (response.statusCode >= 200 && response.statusCode < 300) {
				return response.data;
			}
			const error = new Error(`请求失败，状态码：${response.statusCode}`);
			error.response = response;
			throw error;
		} catch (error) {
			// 统一错误处理
			this._handleError(error);
			throw error;
		}
	}

	// 错误处理
	_handleError(error) {
		const errorMap = {
			400: '请求参数错误',
			401: '未授权，请重新登录',
			403: '拒绝访问',
			404: '请求资源不存在',
			500: '服务器错误',
			502: '网关错误',
			503: '服务不可用',
			504: '网关超时'
		};
		if (error.response) {
			error.message = errorMap[error.response.statusCode] || '未知错误';
		}else if (error.errMsg) {
			error.message = error.errMsg;
		}else {
			error.message = '未知错误';
		}
		console.error(error);


	}

	// 合并配置
	_mergeConfig(config) {
		return {
			...this.config,
			...config,
			header: { ...this.config.header, ...config.header }
		};
	}

	// 添加请求拦截器
	addRequestInterceptor(interceptor) {
		this.requestInterceptors.push(interceptor);
	}

	// 添加响应拦截器
	addResponseInterceptor(interceptor) {
		this.responseInterceptors.push(interceptor);
	}
}

// 创建实例
const request = new Request();
request.addRequestInterceptor(async (config)=>{
	let token = wx.getStorageSync('token')
	let freshToken = wx.getStorageSync('refreshToken')
	if (!token) {
		await login()
		token = wx.getStorageSync('token')
	}
	if (cheakTokenExpired(token)){
		try {
			const newToken = await refreshToken(freshToken)
			wx.setStorageSync('token', newToken)
			token = newToken
		}
		catch (error) {
			await login()
			token = wx.getStorageSync('token')
		}
	}

	config.header['Authorization'] = `Bearer ${token}`
})

module.exports = {request, login}